<template>
  <div class="hello">
    <h1>imeiCheck</h1>
    <input type="text" v-model="imei"></input>
    <button @click="check">check</button>
    <h2 v-text="result"></h2>
  </div>
</template>

<script>
export default {
  name: 'imeicheck',
  data() {
    return {
      imei: '',
      result: ''
    }
  },
  watch: {
    imei(value) {
      if (value.length == 15) {
        this.check()
      } else {
        this.result = '';
      }
    }
  },
  methods: {
    imeiCheck(imei) {
      if (imei.length < 14) {
        return '';
      } else {
        const t = imei.slice(0, 14);
        let resultInt = 0;
        for (let i = 0; i < 14; i++) {
          let a = parseInt(t[i]);
          i++;
          const temp = parseInt(t[i]) * 2;
          let b = temp < 10 ? temp : temp - 9;
          resultInt += a + b;
        }
        resultInt %= 10;
        resultInt = resultInt == 0 ? 0 : 10 - resultInt;
        return resultInt.toString();
      }
    },
    check() {
      const imei = this.imei;
      const r = this.imeiCheck(imei);
      if (r === '') {
        this.result = '错误';
      } else {
        if (r === imei.charAt(14)) {
          this.result = '校验成功 ' + r;
        } else {
          this.result = '校验失败 ' + r;
        }
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>
